package com.yourbatis;

import com.yourbatis.interpreter.Interpreter;
import com.yourbatis.lexical.Lexer;
import com.yourbatis.lexical.Token;
import com.yourbatis.syntax.Syntax;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DynamicProxyHandler implements InvocationHandler {

    private final Class target;

    private MapperFile mapperFile;

    public DynamicProxyHandler(Class target, MapperFile mapperFile) {
        this.target = target;
        this.mapperFile = mapperFile;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before method: " + method.getName());
//        Object result = method.invoke(target, args);
        // 获取方法参数
        Parameter[] parameters = method.getParameters();
        Map map = new HashMap<String, Object>();
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            if (parameter.isAnnotationPresent(Param.class)) {
                Param paramAnnotation = parameter.getAnnotation(Param.class);
                System.out.println("Parameter Name: " + paramAnnotation.value());
                map.put(paramAnnotation.value(), args[i]);
            }
        }
        XMLTree node = mapperFile.getNodeById(method.getName());
        String lookup = node.exec(map);
        System.err.println(lookup);


        System.out.println("After method: " + method.getName());
        return null;
    }


}
